package com.iweb.tmall.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iweb.tmall.entity.User;
import com.iweb.tmall.global.ErrorEnum;
import com.iweb.tmall.global.ResponseData;
import com.iweb.tmall.mapper.UserMapper;
import com.iweb.tmall.param.UserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseData getList(UserParam param) {
        ResponseData responseData = null;
        Page<User> page = new Page<>(param.getCurrent(), param.getSize());
        LambdaQueryWrapper<User> qw = getLambdaQueryWrapper();
        qw.like(param.getUsername()!=null,User::getUsername,param.getUsername());
        qw.eq(param.getIsDelete()!=null,User::getIsDelete,param.getIsDelete());
        page = userMapper.selectPage(page,qw);
        responseData = new ResponseData(page);
        return responseData;
    }

    @Override
    public ResponseData deleteById(Integer id) {
        ResponseData responseData = null;
        User user = new User();
        user.setId(id);
        user.setIsDelete("1");
        int row = userMapper.updateById(user);
        if (row > 0){
            responseData = new ResponseData("删除成功");
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }

        return responseData;
    }

    @Override
    public ResponseData updateById(User entity) {
        ResponseData responseData = null;
        int rows = userMapper.updateById(entity);

        if (rows > 0){
            responseData = new ResponseData(entity);
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }

        return responseData;
    }

    @Override
    public ResponseData save(User entity) {
        ResponseData responseData = null;
        int row = userMapper.insert(entity);
        if (row > 0){
            responseData = new ResponseData(entity);
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }
        return responseData;
    }

    @Override
    public ResponseData getById(Integer id) {
        return null;
    }

    @Override
    public ResponseData check(String name) {
        ResponseData responseData =null;
        LambdaQueryWrapper<User> qw = getLambdaQueryWrapper();
        qw.eq(User::getUsername,name);
        User one = userMapper.selectOne(qw);
        responseData = new ResponseData(one);
        return responseData;
    }
}
